package com.zon.len.dynamic;

import com.zon.len.dynamic.annocation.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author ZonLen since on 2021/12/31 下午1:26
 */
@Slf4j
@Aspect
@Component
public class SwitchDataSourceAspect {

  @Pointcut("@annotation(dynamicDataSource)")
  public void switchPointCut(DynamicDataSource dynamicDataSource) {
  }

  @Around(value = "switchPointCut(dynamicDataSource)", argNames = "joinPoint, dynamicDataSource")
  public Object doExecuteOperation(ProceedingJoinPoint joinPoint,
      DynamicDataSource dynamicDataSource)
      throws Throwable {
    try {
      DataSourceContextHolder.switchDataSource(dynamicDataSource.value());
      if (log.isDebugEnabled()){
        log.debug("Execute Datasource key [{}]", dynamicDataSource.value().name());
      }
      return joinPoint.proceed();
    } finally {
      DataSourceContextHolder.release();
    }
  }
}
